package com.lagou.client;

import com.lagou.server.service.dto.RpcResponse;
import com.lagou.server.service.util.ZookeeperUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 用户客户端处理类
 * @author yzh
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;

    private Map result;

    private Object para;

    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 接收响应的方法
     * @param ctx
     * @param msg
     */
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        RpcResponse rpcResponse = (RpcResponse)msg;
        result = (Map)rpcResponse.getResult();
        notify();
    }

    /**
     * 发送调用请求的方法
     * @return
     * @throws InterruptedException
     */
    public synchronized Object call() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        context.writeAndFlush(para);
        wait();
        long endTime = System.currentTimeMillis();
        long resopnseTime = endTime - startTime;
        System.out.println("----------响应时间为"+resopnseTime+"----------");
        if(!ZookeeperUtil.getZkClient().exists(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/responseTime")) {
            ZookeeperUtil.getZkClient().createEphemeral(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/responseTime", resopnseTime+"");
        } else {
            ZookeeperUtil.getZkClient().writeData(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/responseTime", resopnseTime+"");
        }
        if(!ZookeeperUtil.getZkClient().exists(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/endTime")) {
            ZookeeperUtil.getZkClient().createEphemeral(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/endTime", endTime+"");
        } else {
            ZookeeperUtil.getZkClient().writeData(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/endTime", endTime+"");
        }
        new Thread(() -> {
            try {
                Thread.sleep(5000);
                if( System.currentTimeMillis() - (Long.parseLong(ZookeeperUtil.getZkClient().readData(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/endTime"))) > 5000) {
                    ZookeeperUtil.getZkClient().writeData(ZookeeperUtil.ROOT_PATH+"/response/"+result.get("host")+"/responseTime", "0");
                    System.out.println("响应时间已更新");
                };
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        return result;
    }

    public void setPara(Object para) {
        this.para = para;
    }

}